package jok.array;

public class ArrayDemo {

	public static void main(String[] args) {
		int[] arr = { 2, 6, 3, 4, 15, 21, 9, 1, 31, 12 };

		System.out.println("原数组：");
		showArray(arr);

		System.out.println("排序后：");
		bubbleSort(arr);
		showArray(arr);

		int value = 2;
		System.out.println(value + "的索引为：" + binarySearch(arr, value));
		System.out.println();

		System.out.println("倒置后：");
		invertArray(arr);
		showArray(arr);
	}

	// 冒泡排序（从大到小）
	public static void bubbleSort(int[] array) {
		for (int j = 0; j < array.length - 1; j++) {
			for (int i = 0; i < array.length - j - 1; i++) {
				if (array[i] < array[i + 1]) {
					int temp = array[i];
					array[i] = array[i + 1];
					array[i + 1] = temp;
				}
			}
		}
	}

	// 二分法查找
	public static int binarySearch(int[] array, int value) {
		int minIndex = 0;
		int maxIndex = array.length - 1;
		int midIndex = (maxIndex + minIndex) / 2;

		while (value != array[midIndex]) {
			if (value > array[midIndex]) {
				maxIndex = midIndex;
			} else if (value < array[midIndex]) {
				minIndex = midIndex + 1;
			}
			midIndex = (maxIndex + minIndex) / 2;
		}
		return midIndex;
	}

	// 数组倒置
	public static void invertArray(int[] array) {
		for (int i = 0; i < array.length / 2; i++) {
			int temp = array[i];
			array[i] = array[array.length - i - 1];
			array[array.length - i - 1] = temp;
		}
	}

	// 输入数组所有元素
	public static void showArray(int[] array) {
		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i] + "\t");
		}
		System.out.println();
	}
}
